package org.gabrielnegri.fitparser;

import java.io.File;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;

import org.gabrielnegri.fitparser.entities.TrainingCenterDatabaseT;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

/**
 * Main for FITParser
 * 
 * @author gabriel.negri
 *
 */
public class FITParser {

	@SuppressWarnings("unchecked")
	/**
	 * Parse a FIT File
	 * 
	 * @param filename the FIT File
	 * @return an TrainingCenterDatabaseT object
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws JAXBException
	 */
	public static TrainingCenterDatabaseT parse(String filename)
			throws IOException, InterruptedException, JAXBException {
		Process p = Runtime.getRuntime().exec("fit2tcx --convert" + filename);
		p.waitFor();

		JAXBContext jaxbContext = JAXBContext
				.newInstance(TrainingCenterDatabaseT.class);
		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

		File tcxfile = new File(filename.replaceAll("\\.fit", ".tcx"));
		TrainingCenterDatabaseT trainingCenterDatabase = ((JAXBElement<TrainingCenterDatabaseT>) unmarshaller
				.unmarshal(tcxfile)).getValue();
		tcxfile.delete();
		trainingCenterDatabase.populate();
		return trainingCenterDatabase;
	}

	/**
	 * Parse FIT File and return a JSON String
	 * 
	 * @param args
	 *            full path to FIT File
	 */
	public static void main(String[] args) {
		String result;

		GsonBuilder gsonBuilder = new GsonBuilder();
		gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class,
				new XMLGregorianCalendarConverter.Serializer());
		gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class,
				new XMLGregorianCalendarConverter.Deserializer());
		gsonBuilder.excludeFieldsWithoutExposeAnnotation();
		Gson gson = gsonBuilder.create();

		try {
			if (args.length != 1) {
				throw new FITParserException("No FIT file supplied");
			}

			TrainingCenterDatabaseT trainingCenterDatabaseT = FITParser
					.parse(args[0]);

			result = gson.toJson(trainingCenterDatabaseT,
					TypeToken.get(TrainingCenterDatabaseT.class).getType());
		} catch (FITParserException ex) {
			result = gson.toJson(ex);
		} catch (Exception ex) {
			result = gson.toJson(new FITParserException(
					"Error parsing. See details bellow.", ex));
		}
		System.out.println(result);
	}
}
